package com.plugin.sproutcore.core.resources.properties;

import java.io.File;
import java.io.IOException;

import org.eclipse.core.resources.IProject;

import com.plugin.sproutcore.util.XStreamUtil;

/**
 * Static class used to load and save the properties file.
 */
public class PropertiesLoader 
{
	public static final String FILE_NAME = ".sproutcore";
    public static final String DEFAULT_CHARSET = "UTF-8";
    
    /**
     * Load the properties file from a specified project.
     * 
     * @param project
     * Project where the properties file is to be found and loaded.
     * 
     * @return SproutCore properties object.
     * @throws IOException 
     */
    public static SproutCoreProperties load(IProject project) 
    throws IOException 
    {	
		File file = getPropertiesFile(project);
        if (file.exists()) 
        {
        	SproutCoreProperties properties = null;
        	properties = XStreamUtil.load(file, SproutCoreProperties.class, 
        			DEFAULT_CHARSET);
        	return properties;
        }
        return SproutCoreProperties.getDefaultProperties();
	}
    
	/**
	 * Save the properties object to the properties file.
	 * @param project
	 * The project where the properties file is located.
	 * @param newProperties
	 * The SproutCore properties object to save.
	 * @throws IOException
	 */
	public static void save(IProject project, SproutCoreProperties 
			newProperties) 
	throws IOException 
	{
		File file = getPropertiesFile(project);
		XStreamUtil.save(file, newProperties, DEFAULT_CHARSET); 
	}
	
	/**
	 * Delete the properties file.
	 * @param project
	 * @throws IOException
	 */
	public static void delete(IProject project) 
	throws IOException 
	{
		File file = getPropertiesFile(project);
		boolean success = file.delete();
		if (success == false) {
			throw new IOException("Failed to delete properties");
		}
	}
    
	/**
	 * Get the actual properties file in a project.
	 * @param project
	 * The project where the properties file is located.
	 * @return The properties file.
	 * @throws IOException 
	 */
    public static File getPropertiesFile(IProject project) 
    {
    	return project.getFile(FILE_NAME).getLocation().toFile();
    }
}
